<template>
  <lay-container fluid="true" style="padding: 10px" class="consoles">
    <lay-row space="10">
      <lay-col md="8" v-show="btnIcon">
        <lay-card class="select_box">
          <div class="left_alter">
            <div>
              <!-- <lay-select
                v-model="value"
                placeholder="请选择人员"
                @change="getTableList"
                class="ml"
              >
                <lay-select-option
                  v-for="(item, index ) in userList"
                  :key="index"
                  :value="item.userid"
                  :label="item.username"
                ></lay-select-option>
              </lay-select> -->
              <div>
                当前选择人员:
                <lay-tag type="primary">{{
                  manager.length ? manager : "所有人"
                }}</lay-tag>
              </div>
              <lay-tree
                :data="userList"
                title="username"
                id="userid"
                @node-click="getTreeNode"
              >
              </lay-tree>
            </div>

            <div>
              <div class="input_name">
                <lay-input
                  v-model="xiangmu"
                  type="text"
                  @blur="GetTestItemInfos"
                  placeholder="请输入项目名称"
                >
                </lay-input>
              </div>
              <div v-for="(item, index) in xiangmuList" :key="index">
                <lay-tag
                  class="tag_box"
                  :type="valueItemId == item.testItemId ? 'primary' : ' '"
                  @click="tabPrject(item)"
                  >{{ item.testItemName }}</lay-tag
                >
              </div>
            </div>
          </div>
        </lay-card>
      </lay-col>
      <lay-col :md="btnIcon ? 16 : 24">
        <lay-card>
          <span @click="btnIcon = !btnIcon">
            <i class="layui-icon layui-icon-shrink-right" v-if="btnIcon"></i>
            <i class="layui-icon layui-icon-spread-left" v-else></i>
          </span>

          <div class="msg_val" v-if="tabs == '0'">
            <div>
              <div style="margin-right: 8px">委托日期</div>
              <lay-date-picker
                v-model="dataTime"
                range
                class="w"
                size="sm"
                :placeholder="['开始日期', '结束日期']"
              ></lay-date-picker>
             
              

              <lay-button @click="updataList" class="btn" type="primary" size="sm"
                >查询
              </lay-button>

            </div>

            <div v-if="httpServer.length">
              <div  style="margin:0 8px">
                <!-- <div style="margin:0 8px">选择状态</div> -->
                <lay-select v-model="optionVal" placeholder="请选择状态" size="sm" :allow-clear="true">
                  <lay-select-option :value="0" label="待认领"></lay-select-option>
                  <lay-select-option :value="1" label="送审中"></lay-select-option>
                  <lay-select-option :value="2" label="待审核"></lay-select-option>
                  <lay-select-option :value="3" label="已审核"></lay-select-option>
                  <lay-select-option :value="4" label="已签发"></lay-select-option>
                  <lay-select-option :value="5" label="已归档"></lay-select-option>
                </lay-select>
                <!-- <div>签发归档时间</div> -->
                <lay-date-picker style="margin:0 8px" :allowClear="true" size="sm"  v-model="rangeTime" range :placeholder="['签发归档开始日期','签发归档结束日期']"></lay-date-picker>

                <!-- <lay-date-picker style="margin:0 8px" size="sm" v-model="issuebDate" placeholder="归档时间" allowClear></lay-date-picker>
                <lay-date-picker size="sm" v-model="issueeDate" placeholder="已签发时间" allowClear></lay-date-picker> -->
              </div>

              <lay-button
                @click="exportXlsx"
                type="primary"
                size="sm"
                class="mr"
                v-if="httpUrls.includes('/Checkmsg/GetPersonStaReport')"
              >
                导出报表
              </lay-button>
            </div>
          </div>

          <lay-table
            v-model:selectedKeys="selectedKeys"
            :columns="columns"
            :dataSource="dataSource"
            :checkbox="checkbox"
            :default-toolbar="false"
            @row="rowClick"
          >
            <template v-slot:status="{ data }">
              <!-- 状态,0待认领，1送审中，2待审核，3已审核，4已签发，5已归档 -->
              <lay-tag v-if="data.status == 0">待认领</lay-tag>
              <lay-tag v-if="data.status == 1">送审中</lay-tag>
              <lay-tag v-if="data.status == 2">待审核</lay-tag>
              <lay-tag v-if="data.status == 3">已审核</lay-tag>
              <lay-tag v-if="data.status == 4">已签发</lay-tag>
              <lay-tag v-if="data.status == 5">已归档</lay-tag>
              <lay-tag v-if="data.status == 6">送审超5天</lay-tag>
              <lay-tag v-if="data.status == 7">送审超10天</lay-tag>
            </template>
            <!-- reportCount -->
            <template v-slot:reportCount="{ data }">
              <div
                @click="
                  (itemStatus = data.status),
                    (current = 1),
                    (limit = 10),
                    getTablezhcx(data)
                "
                style="color: #0000ff; cursor: pointer"
              >
                {{ data.reportCount }}
              </div>
            </template>
          </lay-table>

          <lay-page
            v-if="tabs != '0'"
            v-model="current"
            v-model:limit="limit"
            :pages="pages"
            :total="total"
            :show-count="true"
            :show-limit="true"
            :showSkip="true"
            :show-page="true"
            @change="changePage"
          ></lay-page>

          <lay-layer area="100%" title=" " v-model="lookVisible" :maxmin="true">
            <mearchMsg class="msg_val" @search="getSearch" />
            <lay-table
              id="detectionId"
              v-model:selected-keys="selectedKeys"
              :columns="TableHeaderColumns"
              :dataSource="dataSourceList"
              :checkbox="checkbox"
              :default-toolbar="['filter']"
              :cell-style="cellStyle"
            >
              <template v-slot:status="{ data }">
                <!-- 状态,0待认领，1送审中，2待审核，3已审核，4已签发，5已归档 -->
                <!-- @click="claimTag(data)" -->
                <div>
                  <lay-tag type="primary" v-if="data.status == 0">待认领</lay-tag>
                  <lay-tag type="normal" v-if="data.status == 1">送审中</lay-tag>
                  <lay-tag type="normal" v-if="data.status == 2">待审核</lay-tag>
                  <lay-tag type="normal" v-if="data.status == 3">已审核</lay-tag>
                  <lay-tag type="normal" v-if="data.status == 4">已签发</lay-tag>
                  <lay-tag type="normal" v-if="data.status == 5">已归档</lay-tag>
                </div>
              </template>
            </lay-table>
            <lay-page
              v-model="current"
              v-model:limit="limit"
              :pages="pages"
              :total="total"
              :show-count="true"
              :show-limit="true"
              :showSkip="true"
              :show-page="true"
              @change="changePage"
            ></lay-page>
          </lay-layer>
        </lay-card>
      </lay-col>
    </lay-row>
  </lay-container>
</template>
<script lang="ts">
import { isTemplateElement } from "@babel/types";
import { defineComponent, ref, onMounted, reactive, toRefs, onBeforeMount } from "vue";
import {
  ObjectStatusCountSta,
  GetUsers,
  GetPersonSta,
  GetUnclaims,
  GetSubmitting,
  GetCheckPending,
  GetExamine,
  GetSignissue,
  GetFiledlist,
  GetTestItemInfo,
  GetPersonStaReport,
  DetectionObjectSearch,
} from "../../../api/module/user";
import { postDowlod } from "../../../api/request";
import { httpServer } from "../../../api/config";
import qs from "qs";
import { layer } from "@layui/layui-vue";
import mearchMsg from "../zhcx/component/search.vue";

export default defineComponent({
  components: {
    mearchMsg,
  },
  setup() {
    const columns = [
      {
        title: "序号",
        width: "60px",
        type: "number",
        fixed: "left",
      },
      {
        title: "状态",
        customSlot: "status",
        ellipsisTooltip: true,
      },
      {
        title: "报告数量",
        customSlot: "reportCount",
        ellipsisTooltip: true,
      },
      {
        title: "检测数量",
        key: "pointsofTests",
      },
      {
        title: "单位",
        key: "unit",
      },
    ];

    const cellStyle = function (row: any, column: any, rowIndex: any, columnIndex: any) {
      let arr = ["entrustmentNo", "sampleNo", "reportNo"];
      if (arr.includes(column.key)) {
        return "color:blue";
      }
    };

    const rowClick = (data: any) => {
      console.log(JSON.stringify(data));
    };

    const selectedKeys = ref();
    const checkbox = ref(true);

    const mainRef = ref();
    let httpUrl: any = ref([]);
    let url: any = sessionStorage.getItem("httpUrl");
    httpUrl.value = JSON.parse(url);
    const data = reactive({
      value: 0 as any,
      itemStatus: 0,
      lookVisible: false,
      httpUrls: httpUrl,
      httpServer: httpServer,
      manager: "",
      tabsItem: 0,
      overDays: 0,
      current: 1,
      btnIcon: true,
      total: 10,
      pages: 0,
      curren: 10,
      limit: 10,
      tabs: "0",
      tabList: [],
      dataSourceList: [] as any,
      xiangmu: "",
      xiangmuPrject: "",
      userName: "",
      xiangmuList: [] as any,
      tongji: {
        bgsl: 0,
        jcds: 0,
        wcl: 0,
        csrw: 0,
        show: -1,
      },
      valueItemId: 0,
      search: {
        projectName: "",
        entrustmentNo: "",
        sampleNo: "",
        testItems: "",
        reportNo: "",
        client: "",
        sampleReceivingBTime: null,
        sampleReceivingETime: null,
      } as any,
      itemTable: [] as any,
      dataTime: [] as any,
      rangeTime: [] as any,
      optionVal: '' as any,
      dataSource: [] as any,
      tabItem: {
        unclaimsCount: 0,
        unclaims5Count: 0,
        unclaims15Count: 0,
        submittingCount: 0,
        checkPendingCount: 0,
        examineCount: 0,
        signissueCount: 0,
        filedCount: 0,
      } as any,
      userList: [
        {
          title: "所有人",
          id: -10,
          children: [],
        },
      ] as any,
      timeData: {} as any,
      TableHeaderColumns: [
        {
          title: "序号",
          width: "60px",
          type: "number",
          fixed: "left",
        },
        {
          title: "检测人员",
          key: "tester",
          width: "180px",
          ellipsisTooltip: true,
        },
        {
          title: "报告管理人",
          key: "manager",
          width: "180px",
          ellipsisTooltip: true,
        },
        {
          title: "状态",
          customSlot: "status",
          width: "100px",
        },

        {
          title: "检测项目",
          key: "testItems",
          width: "180px",
          ellipsisTooltip: true,
        },
        {
          title: "委托编号",
          key: "entrustmentNo",
          width: "180px ",
          ellipsisTooltip: true,
        },
        {
          title: "样品编号",
          key: "sampleNo",
          width: "180px",
          ellipsisTooltip: true,
        },
        {
          title: "报告编号",
          key: "reportNo",
          width: "180px",
          ellipsisTooltip: true,
        },
        {
          title: "检测数量",
          key: "numberofTests",
          width: "80px",
        },
        {
          title: "单位",
          key: "unit",
          width: "80px",
        },
        {
          title: "设备",
          key: "deviceName",
          width: "100px",
          ellipsisTooltip: true,
        },

        {
          title: "结论状态",
          key: "conclusionStatus",
          width: "100px",
        },

        {
          title: "委托单位",
          key: "client",
          width: "200px",
          ellipsisTooltip: true,
        },
        {
          title: "工程名称",
          key: "projectName",
          width: "200px",
          ellipsisTooltip: true,
        },
        {
          title: "施工部位",
          key: "constructionPosition",
          width: "200px",
          ellipsisTooltip: true,
        },
        {
          title: "委托日期",
          key: "entrustmentDate",
          width: "160px",
          ellipsisTooltip: true,
        },
        {
          title: "规格型号",
          key: "model",
          width: "160px",
          ellipsisTooltip: true,
        },
        {
          title: "收样人",
          key: "sampleReceiver",
          width: "80px",
          ellipsisTooltip: true,
        },
        {
          title: "主检人",
          key: "principalInspector",
          width: "100px",
          ellipsisTooltip: true,
        },
        {
          title: "收费金额",
          key: "chargeAmount",
          width: "80px",
          ellipsisTooltip: true,
        },
        {
          title: "批准日期",
          key: "approvalDate",
          width: "160px",
          ellipsisTooltip: true,
        },
        {
          title: "副检人",
          key: "deputyInspector",
          width: "80px",
          ellipsisTooltip: true,
        },
      ] as any,
    });
    onBeforeMount(() => {
      getLastMonth();
    });
    onMounted(() => {
      if (data.httpUrls.includes("/Setting/GetUsers")) {
        getUserList();
      }

      // getTabItem();

      if (data.httpUrls.includes("/Checkmsg/GetPersonSta")) {
        getTableList();
      }

      GetTestItemInfos();
      console.log("/**************");
    });

    const GetTestItemInfos = async () => {
      if (!data.httpUrls.includes("/Setting/GetTestItemInfo")) return;
      let obj = {
        pageIndex: 1,
        pagePerCount: 500,
        condition: data.xiangmu,
      };
      const res: any = await GetTestItemInfo(obj);
      if (res.code == 200) {
        data.xiangmuList = res.data.datas;
        if (res.data.datas.length) {
          // data.valueItemId = res.data.datas[0].testItemId;
          // getTableList();
        }
      }
    };

    const getTableList = async () => {
      if (!data.httpUrls.includes("/Checkmsg/GetPersonSta")) return;
      data.timeData.bt = data.dataTime[0];
      data.timeData.et = data.dataTime[1];
      if (data.timeData.et && !data.timeData.et.length) {
        data.timeData.bt = null;
        data.timeData.et = null;
      }
      // if (data.value) {
      //   let indexs = data.userList.findIndex((item: any) => {
      //     return item.userid === data.value;
      //   });
      //   if (indexs != -1) {
      //     data.manager = data.userList[indexs].username;
      //   }
      // } else {
      //   data.manager = ''
      // }

      let indes = data.xiangmuList.findIndex((item: any) => {
        return item.testItemId === data.valueItemId;
      });

      if (indes != -1) {
        data.xiangmuPrject = data.xiangmuList[indes].testItemName;
      }
      const res: any = await GetPersonSta({
        manager: data.manager,
        testitem: data.xiangmuPrject,
        ...data.timeData,
      });
      if (res.code == 200) {
        data.dataSource = res.data;
        data.tongji.show = 1;
        layer.msg(res.message, { time: 1000 });
        if (res.data.length) {
          res.data.forEach((item: any) => {
            data.tongji.bgsl += item.reportCount;
            data.tongji.jcds += item.pointsofTests;
            data.tongji.csrw += item.incompleteCount;
          });
        } else {
          data.tongji.bgsl = 0;
          data.tongji.jcds = 0;
          data.tongji.csrw = 0;
        }
      }
    };

    const getLastMonth = () => {
      var now = new Date();
      var year = now.getFullYear();
      var month: any = now.getMonth() + 1; //0-11表示1-12月
      var day = now.getDate();
      var dateObj: any = {};
      dateObj.now = year + "-" + month + "-" + day;
      var nowMonthDay = new Date(year, month, 0).getDate(); //当前月的总天数
      if (month - 1 <= 0) {
        //如果是1月，年数往前推一年<br>
        dateObj.last = year - 1 + "-" + 12 + "-" + day;
      } else {
        var lastMonthDay = new Date(year, parseInt(month) - 1, 0).getDate();
        if (lastMonthDay < day) {
          // 1个月前所在月的总天数小于现在的天日期
          if (day < nowMonthDay) {
            //当前天日期小于当前月总天数
            dateObj.last =
              year + "-" + (month - 1) + "-" + (lastMonthDay - (nowMonthDay - day));
          } else {
            dateObj.last = year + "-" + (month - 1) + "-" + lastMonthDay;
          }
        } else {
          dateObj.last = year + "-" + (month - 1) + "-" + day;
        }
      }
      data.timeData.bt = dateObj.last;
      data.timeData.et = dateObj.now;
      data.dataTime.push(data.timeData.bt);
      data.dataTime.push(data.timeData.et);

      // getTimeData()
    };

    // const getTimeData = () => {
    //   var end = new Date();
    // var year = end.getFullYear();
    // var month: any = end.getMonth() + 1;//0-11表示1-12月
    // var day = end.getDate();
    // var dateObj: any = {};
    // dateObj.end = year + '-' + month + '-' + day;
    // var endMonthDay = new Date(year, month, 0).getDate();    //当前月的总天数
    // if(month - data.activeName <= 0){ //如果是1、2、3月，年数往前推一年
    //   var start3MonthDay = new Date((year - 1), (12 - (data.activeName - parseInt(month))), 0).getDate();    //3个月前所在月的总天数
    //   if(start3MonthDay < day){    //3个月前所在月的总天数小于现在的天日期
    //     dateObj.start = (year - 1) + '-' + (12 - (data.activeName - month)) + '-' + start3MonthDay;
    //   }else{
    //     dateObj.start = (year - 1) + '-' + (12 - (data.activeName - month)) + '-' + day;
    //   }
    // }else{
    //   var start3MonthDay = new Date(year, (parseInt(month) - data.activeName), 0).getDate();    //3个月前所在月的总天数
    //   if(start3MonthDay < day){    //3个月前所在月的总天数小于现在的天日期
    //     if(day < endMonthDay){        //当前天日期小于当前月总天数,2月份比较特殊的月份
    //       dateObj.start = year + '-' + (month - data.activeName) + '-' + (start3MonthDay - (endMonthDay - day));
    //     }else{
    //       dateObj.start = year + '-' + (month - data.activeName) + '-' + start3MonthDay;
    //     }
    //   }else{
    //     dateObj.start = year + '-' + (month - data.activeName) + '-' + day;
    //   }
    // }
    // }

    const updataList = (item: any) => {
      getTableList();
    };

    const getUserList = async () => {
      const res: any = await GetUsers({
        pageIndex: 1,
        pagePerCount: 500,
        condition: {
          // username: data.userName,
          // departmentId: 0,
          // roleId: 0,
        },
      });
      if (res.code === 200) {
        res.data.datas.map((item: any) => {
          item.title = item.username;
          item.id = item.userid;
        });
        data.userList[0].children = res.data.datas;
        if (res.data.datas.length) {
          // data.value = res.data.datas[0].userid;
          // getTableList();
        }
      }
    };

    const changePage = (item: any) => {
      data.limit = item.limit;
      data.current = item.current;
      getTablezhcx();
    };

    const exportXlsx = async () => {
      let obj = {
        manager: data.manager,
        status: data.optionVal == '' ? null : data.optionVal, 
        issuebDate: data.rangeTime[0], 
        issueeDate: data.rangeTime[1], 
        ...data.timeData,
      };
      
      window.open(`${httpServer}${"/Checkmsg/GetPersonStaReport"}?${qs.stringify(obj)}`);
      // let res = await GetPersonStaReport(obj);
      // console.log("res", res);

      // if (res.code == 200) {
      //   window.open(
      //     `${httpServer}${"/Checkmsg/GetPersonStaReport"}?${qs.stringify(obj)}`
      //   );
      // }
    };

    const tabPrject = (item: any) => {
      data.valueItemId = item.testItemId;
      getTableList();
    };

    const getTreeNode = (node: any) => {
      if (node.id === -10) {
        data.manager = "";
      } else {
        data.manager = node.username;
      }
      getTableList();
    };

    const getTablezhcx = async (item?: any) => {
      const res = await DetectionObjectSearch({
        pageIndex: data.current,
        pagePerCount: data.limit,
        condition: {
          manager: data.manager,
          entrustmentDateBTime: data.timeData.bt,
          entrustmentDateETime: data.timeData.et,
          status: data.itemStatus,
          ...data.search,
        },
      });
      if (res.code == 200) {
        data.dataSourceList = res.data.datas;
        data.total = res.data.totalCount;
        data.lookVisible = true;
      }
    };

    const getSearch = (item: any) => {
      data.search = {
        ...data.search,
        ...item,
      };
      getTablezhcx();
    };

    return {
      mainRef,
      columns,
      selectedKeys,
      checkbox,
      getSearch,
      cellStyle,
      getTablezhcx,
      getTreeNode,
      tabPrject,
      exportXlsx,
      rowClick,
      ...toRefs(data),
      changePage,
      updataList,
      getTableList,
      GetTestItemInfos,
      getUserList,
    };
  },
});
</script>

<style>
.left_alter {
  width: 100%;
}

.consoles .layui-card .shadow .select_box .layui-card-body {
  width: 100%;
}
</style>
<style lang="less" scoped>
.left_alter {
  div {
    width: 96%;
  }
}

.select_box {
  width: 100%;

  .ml {
    margin-right: 10px;
  }
}

.msg_val {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  justify-content: space-between;

  div {
    display: flex;
    align-items: center;

    .btn {
      margin-left: 12px;
    }
  }
}

.num_box {
  font-size: 26px;
  font-weight: 700;
  margin: 14px 0;

  span {
    margin-right: 20px;
  }
}

.left_alter {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.tag_box {
  cursor: pointer;
  margin-bottom: 8px;
}

.input_name {
  margin-bottom: 12px;
}
</style>
